package com.dftdla.server.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dftdla.dao.service.ChatUserService;
import com.dftdla.result.ResponseResult;
import com.dftdla.server.message.request.LoginRequestMessage;
import com.dftdla.server.message.response.LoginResponseMessage;
import com.dftdla.server.session.Session;
import com.dftdla.util.Code;
import com.dftdla.utils.RedisKey;
import com.dftdlaRedis.cache.RedisCache;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 14501
 */
@Slf4j
@Component
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    @Resource
    private ChatUserService chatUserService;
    @Resource
    private Session session;
    @Resource
    private RedisCache redisCache;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        Long userId = msg.getUserId();
        boolean login = chatUserService.canLogin(userId);

        LoginResponseMessage message;

        if (login) {
            String bind = session.bind(ctx.channel(), userId);
            log.info("登陆成功");
            message = new LoginResponseMessage(true, "登录成功");
            message.setToken(bind);
            //拉取离线消息
            checkMsgCache(ctx.channel(),userId);
        } else {
            log.warn("用户不合法或已登录");
            message = new LoginResponseMessage(false, "用户不合法或已登录");
        }

        ctx.writeAndFlush(new TextWebSocketFrame(new ResponseResult<>(Code.SUCCESS.code,message).toString()));
    }

    private void checkMsgCache(Channel channel,Long userId) {
        //TODO 分布式锁 -》 消息拉取
        List<Object> object = redisCache.getCacheList(RedisKey.userMsgAutoKey(userId));

        if(object == null){
            return;
        }

        channel.writeAndFlush(new TextWebSocketFrame(new ResponseResult<>(Code.SUCCESS.code,object).toString()));
        redisCache.deleteObject(RedisKey.userMsgAutoKey(userId));
    }
}
